package com.wiim.nhapnhap;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.gms.maps.model.LatLng;
import com.wiim.common.ConstantValue;
import com.wiim.common.Utilities;
import com.wiim.common.Utils;
import com.wiim.handler.CMCmdHandler;
import com.wiim.interfaceapp.IServiceCommandResult;
import com.wiim.interfaceapp.LocationCallBack;
import com.wiim.libs.SessionManager;
import com.wiim.libs.WorldUtilities;
import com.wiim.model.UserData;
import com.wiim.ui.FragmentCustomAnimations;
import com.wiim.ui.LoginActivity;

public class SplashScreen extends Activity implements IServiceCommandResult {
	/** The b active event. */
	protected boolean bActiveEvent = true;
	/** The is active app. */
	private boolean isActiveApp = false;
	/** The i time display splash. */
	protected int iTimeDisplaySplash = 1000;
	public static String regId;
	private SessionManager session;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_screen_layout);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // or
				// .detectAll()
				// for
				// all
				// detectable
				// problems
				.penaltyLog().build());
		Display display = getWindowManager().getDefaultDisplay();
		// getGPSLocation();
		int width = display.getWidth();
		int height = display.getHeight();
		Utilities.getGlobalVariable(SplashScreen.this).device_height = height;
		Utilities.getGlobalVariable(SplashScreen.this).device_width = width;
		session = new SessionManager(SplashScreen.this);
		// Thread for displaying the SplashScreen
		Thread splashThread = new Thread() {

			@Override
			public void run() {

				try {
					int iCount = 0;
					while ((SplashScreen.this.bActiveEvent && (iCount < SplashScreen.this.iTimeDisplaySplash)) || !SplashScreen.this.isActiveApp) {
						sleep(100);
						if (SplashScreen.this.bActiveEvent) {
							iCount += 100;
						}

					}
				} catch (InterruptedException e) {
					// do nothing
					e.printStackTrace();
				} finally {
					SplashScreen.this.finish();
					if (Utilities.getGlobalVariable(SplashScreen.this).isLogin) {
						final Intent itTab = new Intent().setClass(SplashScreen.this.getApplicationContext(), MainActivity.class);
						SplashScreen.this.startActivity(itTab);
					} else {
						final Intent itTab = new Intent().setClass(SplashScreen.this.getApplicationContext(), FragmentCustomAnimations.class);
						// Bundle bundle = new Bundle();
						// bundle.putInt("indexTab", 0);
						// itTab.putExtras(bundle);
						SplashScreen.this.startActivity(itTab);
					}

				}
			}
		};
		splashThread.start();

		// isActiveApp = true;
		checkInternetConnection();

	}

	private void checkLogin() {
		if (avail) {
			if (session.isLoggedIn()) {
				HashMap<String, String> user = session.getUserLogin();
				String name = user.get(SessionManager.KEY_NAME);
				String pass = user.get(SessionManager.KEY_PASS);
				UserData uData = new UserData();
				uData.setUsername(name);
				uData.setPassword(pass);
				uData.setDeviceID(Utils.getDeviceID(SplashScreen.this));
				uData.setAccountType(ConstantValue.AccountType.NATIVE.toString());

				Bundle b = new Bundle();
				b.putSerializable(EgoodApp.REST_OBJECT_PUT, uData);
				AppGlobal.getInstance().startServiceCmd(CMCmdHandler.COMMAND_LOGIN_VALIDATE, SplashScreen.this, new CMCmdHandler(), b, false);
			}else{
				isActiveApp=true;
			}
		}

	}

	boolean avail;

	private void checkInternetConnection() {
		avail = WorldUtilities.checkInternetAvailable(this);

		if (!avail) {
			WorldUtilities.showDialogCannotConnectToServer(this, getString(R.string.txt_warning), getString(R.string.msg_internet_not_avail_continue));
			isActiveApp = false;
			// setLocation();
		} else {
			setLocation();
		}

	}

	public void setLocation() {
		Utilities.getGPSLocation(SplashScreen.this, locationCallback);
	}

	LocationCallBack locationCallback = new LocationCallBack() {
		@Override
		public void callback(LatLng position, String result) {
			Utilities.getGlobalVariable(SplashScreen.this).setLatlongDefault(position);
			Utilities.getGlobalVariable(SplashScreen.this).setAddressDefault(result);
			checkLogin();
			// isActiveApp = true;
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		Bundle bResultData = (Bundle) resultData;
		switch (commandCode) {
		case CMCmdHandler.COMMAND_LOGIN_VALIDATE: {
			UserData uData = (UserData) bResultData.getSerializable(EgoodApp.REST_OBJECT_RETURN);

			if (uData.ValidateUserResponse.equalsIgnoreCase(ConstantValue.ValidateUserResponse.SUCCESS.toString())) {
				LoginActivity.u.setUsername(uData.Username);
				LoginActivity.u.setAccountType(uData.AccountType);
				LoginActivity.u.setDeviceID(uData.DeviceID);
				LoginActivity.u.setLastLogin(uData.LastLogin);
				LoginActivity.u.setPassword(uData.Password);
				LoginActivity.u.setUserId(uData.UserId);
				LoginActivity.u.Fullname = uData.Fullname;
				LoginActivity.u.RewardAmount = uData.RewardAmount == null ? "0" : uData.RewardAmount;

				// session.saveLogin(uData.Username, uData.Password, true);
				Utilities.getGlobalVariable(SplashScreen.this).isLogin = true;
			} else {
				Toast.makeText(this, uData.ValidateUserResponse, Toast.LENGTH_LONG).show();
			}
			isActiveApp = true;
		}
			break;

		default:
			break;
		}

	}
}
